package com.kgc.provider;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.kgc.api.user.UserInfoApi;
import com.kgc.bean.User;
import com.kgc.domain.UserExample;
import com.kgc.mapper.UserMapper;
import com.kgc.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * @Author：周申宇 <p>
 * @Date:2021/6/20 14:27
 * <p>
 * @Decription: 用户信息提供者
 */
@Service
@Slf4j
public class UserProvider implements UserInfoApi {
   @Autowired
   private UserMapper userMapper;
   @Autowired
   private RedisUtils redisUtils;

    @Override
    public Boolean phoneIsUsed(String phone) {
        UserExample userExample=new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);
        log.info("**************userMapper.selectByExample(userExample):{}***********",userMapper.selectByExample(userExample));
        if(userMapper.selectByExample(userExample).size()>0){//为什么不能用null比较
            return true;
        }
        return false;
    }

    @Override
    public User selectUserByPhone(String phone) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andPhoneEqualTo(phone);
        return userMapper.selectByExample(userExample).get(0);
    }

    @Override
    public Boolean addUser(User user) {
        if(1== userMapper.insertSelective(user)){
            return true;
        }
        return false;
    }

    @Override
    public Boolean doesOpenidExist(String openid) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andOpenidEqualTo(openid);
        if(userMapper.selectByExample(userExample).size()>0){
            return true;
        }
        return false;
    }

    @Override
    public User findUserBasedOnOpenID(String openid) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andOpenidEqualTo(openid);
        return userMapper.selectByExample(userExample).get(0);
    }

    @Override
    public Boolean doesTheUsernameExist(String username) {
        UserExample userExample = new UserExample();
        UserExample.Criteria criteria=userExample.createCriteria();
        criteria.andUsernameEqualTo(username);
        if(userMapper.selectByExample(userExample).size()>0){
            return true;
        }
        return false;
    }

    @Override
    public Boolean modifyUserInformation(User user) {
        if(userMapper.updateByPrimaryKey(user)==1){
            return true;
        }
        return false;
    }

    @Override
    public Boolean renewingMember(String token) {
        User user= JSON.parseObject(redisUtils.get(token).toString(),User.class);
        if(null==user.getVipBeginTime()){//此账户之前没有开过会员
            Date date=new Date();
            user.setVipBeginTime(date);
        }
        int month=(Integer)redisUtils.get("month");
        Date date=new Date();
        if(null==user.getVipEndTime()||user.getVipEndTime().before(date)){//没开过会员，或者开过会员但是过期了，
            Calendar calendar= Calendar.getInstance();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            calendar.add(Calendar.DATE, month*30);//今天的日期基础上加10天
            String ten_days_after = sdf.format(calendar.getTime());
            try {
                Date vipEndTime=sdf.parse(ten_days_after);
                user.setVipEndTime(vipEndTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }else {//开过会员，并且在会员有效期内
            Date userVipEndTime=user.getVipEndTime();
            Calendar calendar= Calendar.getInstance();
            calendar.setTime(userVipEndTime);//在原来结束时间的基础上加10天+
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            calendar.add(Calendar.DATE, month*30);
            String ten_days_after = sdf.format(calendar.getTime());
            try {
                Date vipEndTime=sdf.parse(ten_days_after);
                user.setVipEndTime(vipEndTime);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        //将会员持久化到数据库
        user.setIsvip(1);
        if(modifyUserInformation(user)){
            redisUtils.set(token, JSON.toJSONString(user));
            redisUtils.del("month");
            return true;

        }else {
            return false;
        }
    }

    @Override
    public Boolean delUserById(Integer userId) {
        log.info("-------------删除用户，用户id：{}",userId);
        return userMapper.deleteByPrimaryKey(userId)>0;
    }

    @Override
    public Integer integralSettlement(Integer userId, Integer actualPayment) {
        log.info("执行积分结算");
        Integer score=0;

        score = userMapper.queryIntegralById(userId)+actualPayment/10;

        log.info("用户：{},本次购买商品可结算的积分为：{}",userId,actualPayment/10);
        if(userMapper.updateIntegral(userId,score)>0){
            log.info("积分结算结束");
            return actualPayment/10;

        }else {
            return -1;
        }


    }

    @Override
    public User queryUserById(Integer userId) {
        return userMapper.selectUserById(userId);
    }

    @Override
    public User findUserBaseOnUserId(Integer userId) {
        return userMapper.selectByPrimaryKey(userId);

    }

    @Override
    public Integer checkIn(Date date,Integer userId) {
        //签到获得的积分数
        Integer signInScore =0;
        //获取当前时间的前一天和最后签到时间的转换的字符串
      SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        Calendar now = Calendar.getInstance();
        now.setTime(date);
        String today =sdf.format(now.getTime());
        now.add(Calendar.DAY_OF_MONTH, -1);
        String previous =sdf.format(now.getTime());

      Date  lastSignDate= userMapper.queryLastSignDate(userId);
     //查询连续签到时间
     Integer signDays = userMapper.querySignDays(userId);
     // 查询用户积分
     Integer integral = userMapper.queryIntegralById(userId);
     //如果最后一次签到时间不为空
      if(lastSignDate!=null) {
          Calendar last = Calendar.getInstance();
          last.setTime(lastSignDate);
          String lastSign = sdf.format(last.getTime());
          //如果系统时间的前一天和最后一次签到时间的日期一致，证明是连续签到
          if (previous.equals(lastSign)) {
              log.info("是连续签到，进行签到操作");
              if (signDays < 6) {
                  signDays += 1;
                  integral += 1;
                  signInScore=1;
                  userMapper.updateSignIn(date,signDays,integral,userId);
                  userMapper.insertSignInfo(userId,date,signInScore);
              } else if (signDays == 6) {
                  integral += 20;
                  signDays = 0;
                  signInScore=20;
                  userMapper.updateSignIn(date,signDays,integral,userId);
                  userMapper.insertSignInfo(userId,date,signInScore);
              }

          } else if(today.equals(lastSign)){
              //如果最后一次签到的日期和当前系统日期一致，说明今天已经签到，不能继续签到
            log.info("今天已经签到完毕，不能继续签到");
          } else {
              //如果最后一次签到时间不满足以上两种情况，原有连续签到天数将进行重置
              log.info("不是连续签到");
              signDays = 1;
              integral += 1;
              signInScore=1;
              userMapper.updateSignIn(date,signDays,integral,userId);
              userMapper.insertSignInfo(userId,date,signInScore);
          }
      }else{
          //如果最后一次签到时间为空，说明从来没有签到
          log.info("第一次签到");
          signDays = 1;
          integral += 1;
          signInScore=1;
          userMapper.updateSignIn(date,signDays,integral,userId);
          userMapper.insertSignInfo(userId,date,signInScore);
      }

        return signInScore;
    }

    @Override
    public Integer collectResolve(String goodsId, Integer userId) {
        Integer flag =userMapper.queryCollect(userId,goodsId);
        log.info("收藏id:{}",flag);

        if(flag!=null){
        log.info("执行取消收藏");
        if(userMapper.deleteCollect((flag))>0){
                return 1;
            }
            return 0;
        }else{
           Date date = new Date();
            log.info("执行移入收藏");
            if(userMapper.moveToCollect(userId,goodsId,date)>0){
                return 2;
            }
            return 0;
        }

    }


}
